// ignore_for_file: unnecessary_overrides, non_constant_identifier_names, constant_identifier_names, unused_local_variable

import 'dart:collection';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:verse_systems/commom/config/config.dart';
import 'package:verse_systems/commom/global/global.dart';
import 'package:verse_systems/commom/models/chat_info_model.dart';
import 'package:verse_systems/commom/provider/common_provider.dart';
import 'package:verse_systems/net/http_dio.dart';
import 'package:verse_systems/pages/home/home_control.dart';
import 'package:verse_systems/pages/service/service_state.dart';
import 'dart:io'; // 导入websocket的包
import 'package:verse_systems/utils/account_util.dart';
import 'dart:convert' as convert;

import 'package:verse_systems/utils/loading.dart';
import 'package:verse_systems/utils/utils.dart';

enum MessageType {
  Text,
  Image,
}

class MessageControl extends GetxController {
  MethodChannel eventChannel = const MethodChannel('open_native_camera');

  final ServiceState state = ServiceState();

  MessageType type = MessageType.Text;

  final ScrollController scrollController = ScrollController();
  final TextEditingController messageController = TextEditingController();
// WebSocket.connect返回的是 Future<WebSocket>对象
  static WebSocket? _webSocket;

  onTapShow() {
    state.chatBottom = !state.chatBottom;
    update();
    scrollToLastItem();
  }

  onUploadTap() async {
    String productUrl = state.path;
    if (await canLaunchUrl(Uri.parse(productUrl))) {
      await launchUrl(Uri.parse(productUrl));
    } else {
      throw 'Could not launch $productUrl';
    }
  }

  onChatTap(Map result) {
    type = MessageType.Image;
    debugPrint("result--$result");
    if (result["index"] == 0) {
      openAlbum();
    } else {
      openCamera();
    }
  }

  openCamera() {
    eventChannel.invokeMethod("open_camera").then((value) async {
      if (Platform.isAndroid) {
        if (value == true) {
          //获取相机授权
          String base64 = await Utils.openCamera();
          uploadImage(base64: base64);
        }
      } else {
        String base64 = value["image"];
        uploadImage(base64: base64);
      }
    });
  }

  openAlbum() {
    eventChannel.invokeMethod("open_album").then((value) async {
      if (Platform.isAndroid) {
        if (value == true) {
          //获取相册授权
          String base64 = await Utils.openAlbum();
          uploadImage(base64: base64);
        }
      } else {
        String base64 = value["image"];
        uploadImage(base64: base64);
      }
    });
  }

  uploadImage({String? base64}) async {
    final home_control = Get.find<HomeControl>();
    Loading.show("uplod_loding".tr);
    final String token = await AccountUtil.getUserToken();
    Map<String, dynamic> map = HashMap();
    map['token'] = token;
    map['borrow_id'] = home_control.state.borrow_id;
    map['img_type'] = "chat";
    map['base64'] = base64;

    Request.postCallback(
      HttpUrls.uploadUrl,
      data: map,
      success: (res) async {
        Loading.dismiss();
        ResultData result = ResultData.fromJson(res.data);
        debugPrint("result-----$result");
        if (result.status == 0) {
          String url = result.data["url"];
          state.messageUrl = result.data["path"];
          state.imageUrl = url;
          postSendMessage();
        }
      },
      error: (err) {
        Loading.dismiss();
      },
    );
  }

  onTapHide() {
    if (state.chatBottom) {
      state.chatBottom = false;
    }
    update();
  }

  void scrollToLastItem() {
    Future.delayed(const Duration(milliseconds: 100), () {
      try {
        scrollController.animateTo(
          scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 200),
          curve: Curves.ease,
        );
        // ignore: empty_catches
      } catch (e) {}
    });
  }

  @override
  void onInit() async {
    super.onInit();
    getChatInfo();
  }

  getChatInfo() async {
    final String token = await AccountUtil.getUserToken();

    Request.postCallback(
      HttpUrls.getChatInfoUrl,
      data: {'token': token},
      success: (res) async {
        ResultData result = ResultData.fromJson(res.data);
        if (result.status == 0) {
          debugPrint("获取客服信息----$result");
          state.pointers_id = result.data["pointers_id"];
          final List records = result.data["records"];
          state.chatList =
              records.map((json) => ChatInfoModel.fromJson(json)).toList();
          state.path = result.data["path"];
          update();
          scrollToLastItem();
          onInitSocket();
        }
      },
    );
  }

  onInitSocket() async {
    final String token = await AccountUtil.getUserToken();
    // 连接WebSocket服务器
 
    final String socket  = Config.getConfigSocket(); 
     Future<WebSocket> webSocketFuture = WebSocket.connect(
        '$socket$token');
    webSocketFuture.then((WebSocket ws) {
      _webSocket = ws;
      _webSocket!.listen(onData, onDone: () {
        debugPrint('onDone');
      }, onError: onError, cancelOnError: true);
      openMessage();
    });
  }

  void onData(dynamic content) {
    final Map jsonCode = convert.jsonDecode(content);

    debugPrint('收到消息:$content');
    BuildContext context = Global.navigatorKey.currentState!.overlay!.context;
    String type = jsonCode["type"];
    switch (type) {
      case "new-message":
        {
          if (Global.isChat == false) {
            Future.delayed(Duration.zero, () {
              Global.count += 1;
              debugPrint('new-message--收到消息:${Global.count}');
              Provider.of<CommonProvider>(context, listen: false)
                  .addIndex(Global.count);
            });
          }

          final Map<String, dynamic> data = jsonCode["data"];

          final timestamp = data["message_time"].toString(); //示例时间戳
          String startDate =
              DateTime.fromMillisecondsSinceEpoch(int.parse(timestamp) * 1000)
                  .toString()
                  .substring(0, 19);
          debugPrint('startDate收到消息:$startDate');
          if (startDate.length >= 19) {
            startDate = startDate.substring(11, 16);
          }
          data["message_time"] = startDate;
          data["send_success"] = true;
          data["read_success"] = true;
          ChatInfoModel chat = ChatInfoModel.fromJson(data);
          state.chatList.add(chat);
          update();
          scrollToLastItem();
          readMessage();
        }

        break;
      case "del-message":
        {
          if (Global.isChat == false) {
            Future.delayed(Duration.zero, () {
              Global.count -= 1;
              if (Global.count < 0) {
                Global.count = 0;
              }
              debugPrint('del-message--收到消息:${Global.count}');
              Provider.of<CommonProvider>(context, listen: false)
                  .addIndex(Global.count);
            });
          }
          //删除消息通知
          debugPrint('heartbeat--收到消息:$content');
          final records_id = jsonCode["data"]["records_id"];
          debugPrint('删除消息通知--收到消息:$records_id');
          state.chatList
              .removeWhere((element) => element.recordsId == records_id);
          update();
        }
        break;

      case "read":
        {
          //收到消息变为已读
          final List<ChatInfoModel> chatList = state.chatList;
          for (var element in chatList) {
            element.readSuccess = true;
          }
          state.chatList = chatList;
          update();
        }
        break;
      default:
    }
  }

  handleSend() async {
    if (messageController.text.trim() == "") {
      return Loading.showError("请输入发送的消息内容");
    }
    type = MessageType.Text;
    postSendMessage();
  }

  postSendMessage() async {
    final String token = await AccountUtil.getUserToken();
    Map<String, dynamic> map = HashMap();
    map['token'] = token;
    map['pointers_id'] = state.pointers_id;
    if (type == MessageType.Text) {
      map['message_type'] = 0;
      map['message'] = messageController.text.trim();
    } else {
      map['message_type'] = 1;
      map['message'] = state.messageUrl.toString();
    }

    Request.postCallback(
      HttpUrls.sendChatInfoUrl,
      data: map,
      success: (res) async {
        ResultData result = ResultData.fromJson(res.data);
        if (result.status == 0) {
          final Map<String, dynamic> data = result.data;
          debugPrint('handleSend消息:$result');
          send_message(map: data);
        }
      },
    );
  }

  send_message({required Map<String, dynamic> map}) {
    map["read"] = 1;
    map["send"] = true;
    map["send_success"] = true;
    map["read_success"] = false;
    ChatInfoModel chat = ChatInfoModel.fromJson(map);
    state.chatList.add(chat);

    update();
    scrollToLastItem();
    messageController.clear();
  }

  void onError(dynamic error) {
    debugPrint('连接WebSocket服务器--error消息:$error');
  }

  //打开会话
  void openMessage() {
    String jsonString = convert.jsonEncode({
      "type": "open-message",
      "data": {"pointers_id": state.pointers_id}
    });
    debugPrint('打开会话发送消息:---$jsonString');
    _webSocket!.add(jsonString);
  }

  //关闭会话
  closeMessage() {
    String jsonString =
        convert.jsonEncode({"type": "close-message", "data": {}});
    debugPrint('关闭会话发送消息:---$jsonString');
    if (_webSocket != null) {
      _webSocket!.add(jsonString);
    }
  }

  //被动接收消息已读
  readMessage() {
    String jsonString = convert.jsonEncode({
      "type": "read",
      "data": {"pointers_id": state.pointers_id}
    });
    debugPrint('被动接收消息已读:---$jsonString');
    _webSocket!.add(jsonString);
  }

//新消息推送
  newMessage() {
    String jsonString = convert.jsonEncode({
      "type": "new-message",
      "data": {
        "records_id": "消息id「string」",
        "pointers_id": "会话id「string」",
        "name": "姓名「string」",
        "icon": "头像「string」",
        "message": "消息内容「string」",
        "message_type": "消息类型「integer」", // 0-文本，1-图像
        "message_time": "消息时间戳「integer」"
      }
    });
    debugPrint('新消息推送:---$jsonString');
    _webSocket!.add(jsonString);
  }

//撤回消息后删除消息
  delMessage(value) {
    String jsonString = convert.jsonEncode({
      "type": "del-message",
      "data": {"pointers_id": state.pointers_id, "records_id": value}
    });
    state.chatList.removeWhere((element) => element.recordsId == value);
    update();
    debugPrint('撤回消息后删除消息:---$jsonString');
    _webSocket!.add(jsonString);
  }

  @override
  void onClose() {
    super.onClose();
    // 关闭WebSocket连接
    closeMessage();
    if (_webSocket!=null) {
           _webSocket!.close();
    } 

    Global.count = 0;
    debugPrint('关闭WebSocket连接');
  }
}
